<?php
/**
 * 财富相关接口
 * */

namespace App\Http\Controllers;

use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FormatCheck;
use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\Room;
use App\Http\Model\User;
use App\Http\Services\FinanceServices;
use App\Http\Services\MsgServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Services\RoomServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use App\Lib\Response;

class FinanceController extends BaseController
{
    protected $request;
    protected $service;
    protected $user;
    protected $plat_type = [1, 2]; //1:IOS 2：Android
    protected $charts_type = [1,2,3,4,5];//榜单类型
    protected $serviceMsg;
    protected $serviceRoom;
    protected $serviceRoomMsg;

    public function __construct(FinanceServices $service, Request $request)
    {
        $this->request = $request;
        $this->service = $service;
        $this->serviceMsg = new MsgServices();
        $this->serviceRoom = new RoomServices();
        $this->serviceRoomMsg = new RoomMsgServices();
    }

    /**
     * @desc 账户信息
     * @date 2018/12/20
     * */
    public function cash()
    {
        $this->service->checkToken();
        $walletData = $this->service->getUserCach();
        if (!empty($walletData)) {
            Response::returnResult(Hint::SUCCESS, $walletData);
        } else {
            Response::returnResult(Hint::ERROR);
        }
    }

    /**
     * @desc 充值规则
     * @param
     * @date 2018/12/20
     * */
    public function pay_rules()
    {
        $platform = $this->request->get('platform');
        $from = $this->request->get('from',0);//1=h5来源 0=默认APP
        if (empty($platform)){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $diamond = $this->service->getDiamondRule($platform);
        if(!empty($from)){
            Response::returnResult(Hint::SUCCESS, $diamond,'ok',0);
        }else{
            Response::returnResult(Hint::SUCCESS, $diamond);
        }
        
    }

    /**
     * 获取支付类型
     */
    public function getPayTypeList(Request $request)
    {
        $ua = $request->userAgent();
        $userAgent = explode(';',$ua);
        $data = $this->service->getPayTypeList($userAgent);

        Response::returnResult(Hint::SUCCESS,$data);
    }


    /**
     * 提现规则
     */
    public function withdraw_rules(){
        $data = $this->service->get_kk_rules();
        OutJson::outJsonResult(Hint::SUCCESS, $data);
    }

    /**
     * @desc 魅力值明细列表
     * @date 2018/12/20
     * */
    public function charm_detail_list()
    {
        $this->service->checkToken();

        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $streamList = $this->service->getCharmStreamList($page, $page_size);

        OutJson::outJsonResult(Hint::SUCCESS, $streamList);
    }

    /**
     * @desc 钻石明细列表
     * @date 2018/12/20
     * */
    public function diamond_detail_list()
    {

            $this->service->checkToken();

            $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
            $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

            $streamList = $this->service->getDiamondStreamList($page, $page_size);

            Response::returnResult(Hint::SUCCESS, $streamList);
    }


    /**
     * @desc 金币明细列表
     * @date 2018/12/20
     * */
    public function kk_detail_list()
    {
        $this->service->checkToken();

        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $streamList = $this->service->getKkStreamList($page, $page_size);

        Response::returnResult(Hint::SUCCESS, $streamList);
    }

    /**
     * @desc 获取排行榜部分数据
     * */
    public function get_rank_appoint()
    {
        $type = 3;
        $page = 0;
        $page_size = 3;

        //富豪榜
        $data = $this->service->getWealthCharts($type,$page,$page_size);
        $result['wealth_charts'] = empty($data['list']) ? [] : $data['list'];
        //魅力榜
        $data = $this->service->getCharmCharts($type,$page, 20);
        $result['charm_charts'] = empty($data['list']) ? [] : array_slice($data['list'], 0, 3);

        Response::returnResult(Hint::SUCCESS, $result);
    }

    /**
     * @desc 富豪榜[财富流水]
     * @param int $type [1:日 2：周 3：总]
     * @date 2018/12/20
     * */
    public function wealth_charts()
    {

            $type = (int)$this->request->get('type'); //1:日 2：周 3：总
            if (!$type || !in_array($type, $this->charts_type))
                Response::returnResult(Hint::PARAM_ERROR);

            $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
            $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

            $result = $this->service->getWealthCharts($type,$page,$page_size);
            Response::returnResult(Hint::SUCCESS,$result);


    }


    /**
     * @desc 房间富豪榜[财富流水]
     * @param int $type [1:日 2：周 3：总 4:昨日 5:上周]
     * @date 2018/12/20
     * */
    public function room_wealth_charts()
    {
        $userId = $this->getLoginUserId();

        $room_id = $this->request->get('room_id');
        if ($room_id == null){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $type = (int)$this->request->get('type'); //1:日 2：周 3：总 4:昨日 5:上周
        if (!$type || !in_array($type, $this->charts_type)){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $result = $this->service->getRoomWealthCharts($userId, $room_id,$type,$page,$page_size);
        Response::returnResult(Hint::SUCCESS,$result);
    }

    /**
     * @desc 魅力榜[魅力流水+]
     * @param int $type [1:日 2：周 3：总]
     * @date 2018/12/30
     * */
    public function charm_charts()
    {

           $type = (int)$this->request->get('type'); //1:日 2：周 3：总
           if (!$type || !in_array($type, $this->charts_type))
               Response::returnResult(Hint::PARAM_ERROR, []);

           $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
           $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

           $result = $this->service->getCharmCharts($type,$page,$page_size);
           Response::returnResult(Hint::SUCCESS,$result);

    }


    /**
     * @desc 房间魅力榜[魅力流水+]
     * @param int $type [1:日 2：周 3：总 4:昨日 5上周]
     * */
    public function room_charm_charts()
    {
        $userId = $this->getLoginUserId();

        $room_id = $this->request->get('room_id');
        if (empty($room_id)){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $type = (int)$this->request->get('type'); //1:日 2：周 3：总 4昨日 5上周
        if (!$type || !in_array($type, $this->charts_type)){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $result = $this->service->getRoomCharmCharts($userId, $room_id, $type,$page,$page_size);
        Response::returnResult(Hint::SUCCESS,$result);
    }



    public function room_self_wealth_charts(){
        $type = (int)$this->request->get('type'); //1:日 2：周 3：总
        if (!$type || !in_array($type, $this->charts_type))
            Response::returnResult(Hint::PARAM_ERROR, []);

        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $result = $this->service->getRoomSelfWealthCharts($type,$page,$page_size);
        Response::returnResult(Hint::SUCCESS,$result);
    }

    /**
     * 根据参数 $date 获取当月得房间收益
     * @param Request $request
     */
    public function get_finance_room_wealth_list(Request $request){
        $date = (int) $request->get('date',0);
        if(!$date){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
        }
        $room_id = (int) $request->get('room_id',0);

        OutJson::outJsonResult(Hint::SUCCESS, $this->service->get_finance_room_wealth_list($date, $room_id));
    }

    /**
     * 房间收益详情
     * @param Request $request
     */
    public function get_finance_wealth_stream(Request $request){
        $date = (int) $request->get('date',0);
        $page = (int) $request->get('page_index', 0);
        $length = (int) $request->get('page_size', 20);
        $startTime = (int) $request->get('start_time', 0);
        $endTime = (int) $request->get('end_time', 0);
        $roomId = (int) $request->get('room_id', 0);

        if(!$date){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
        }
        if (empty($startTime) || empty($endTime)){
            $startTime = strtotime(date('Y-m-d 00:00:00', $date));
            $endTime = strtotime(date('Y-m-d 23:59:00', $date));
        }
        $list = $this->service->get_finance_wealth_stream($startTime, $endTime, $page, $length, $roomId);
        OutJson::outJsonResult(Hint::SUCCESS,$list);
    }

    /**
     * 房间收益详情
     * @param Request $request
     */
    public function getFinanceWealthStreamTotal(Request $request){
        $date = (int) $request->get('date',0);
        $page = (int) $request->get('page_index', 0);
        $length = (int) $request->get('page_size', 20);
        $startTime = (int) $request->get('start_time', 0);
        $endTime = (int) $request->get('end_time', 0);
        $roomId = (int) $request->get('room_id', 0);
        if(!$date){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
        }
        if (empty($startTime) || empty($endTime)){
            $startTime = strtotime(date('Y-m-d 00:00:00', $date));
            $endTime = strtotime(date('Y-m-d 23:59:00', $date));
        }
        $list = $this->service->get_finance_wealth_stream($startTime, $endTime, $page, $length, $roomId);
        $total = $this->service->getFinanceWealthStreamTotal($startTime, $endTime ,$roomId);
        $data = [
            'total_value' => $total,
            'list' => $list,
        ];
        OutJson::outJsonResult(Hint::SUCCESS,$data);
    }

    /**
     * 后台钻石-加减
     * @param Request $request
     */
    public function set_diamond_balance(Request $request){
        $this->service->set_cross();
        $diamond_balance = (int) $request->post('diamond_balance',0);
        $user_id = (int) $request->post('user_id',0);
        if(!$user_id || !$diamond_balance){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
        }

        $this->service->set_diamond_balance($user_id, $diamond_balance);
        OutJson::outJsonResult(Hint::SUCCESS);
    }

    /**
     * 后台金币接口
     * @param Request $request
     */
    public function minusKkValue(Request $request){
        $this->service->set_cross();
        $kkValue = (int) $request->post('kk_value',0);
        $userId = (int) $request->post('user_id',0);
        if(!$kkValue || !$userId){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
            return;
        }
        $res = $this->service->minusKkValue($userId, $kkValue);
        if ($res['code'] == Hint::SUCCESS) {
            Response::returnResult(Hint::SUCCESS);
        } else {
            Response::returnResult($res['code'], $res['data'], $res['msg']);
        }

    }


    /**
     * 金币系统操作
     * @param Request $request
     */
    public function incKkValue(Request $request){
        $this->service->set_cross();
        $kkValue = (int) $request->post('kk_value',0);
        $userId = (int) $request->post('user_id',0);
        $desc = (string) $request->post('desc','系统操作');
        if(!$kkValue || !$userId){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
            return;
        }
        $this->service->incKkValue($userId, $kkValue, $desc);
        OutJson::outJsonResult(Hint::SUCCESS);
    }



    /**
     * 钻石系统操作
     * @param Request $request
     */
    public function incDiamondValue(Request $request){
        $this->service->set_cross();
        $diamondValue = (int) $request->post('diamond_value',0);
        $userId = (int) $request->post('user_id',0);
        $desc = (string) $request->post('desc','系统操作');
        if(!$diamondValue || !$userId){
            OutJson::outJsonResult(Hint::PARAM_ERROR);
            return;
        }
        $this->service->incDiamondValue($userId, $diamondValue, $desc);
        OutJson::outJsonResult(Hint::SUCCESS);
    }

    /**
     * 金币兑换
     * @param Request $request
     */
    public function exchange(Request $request){
        $kk_val = (int) $request->get('kk_val');
        $accountPwd = $request->get('account_password','');// 账户密码
        if (empty($kk_val)){
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        // if($kk_val<100 || !($kk_val%100==0)) {
        //     Response::returnResult(Hint::PARAM_ERROR, [], '每次只能兑换100的倍数');
        // }

        $data = $this->service->exchange($kk_val,$accountPwd);
        if(!is_array($data)){
            Response::returnResult($data);
        }

        Response::returnResult($data['code']);
    }

    /**
     * 校验账户是否设置密码
     */
    public function checkAccountPassword()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->service, 'checkAccountPassword', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 设置账户密码（设置密码、修改密码、忘记密码）
     */
    public function setAccountPassword()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            /*$phone = $this->requestData['phone'] ?? '';
            if(empty($phone)){
                $this->requestData['phone'] = $this->userInfo['phone'];
            }*/
            $this->requestData['phone'] = $this->userInfo['phone'];
            $this->callCommon($this->service, 'setAccountPassword', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * wap 金币明细
     * */
    public function queryKKStreamByUserId(Request $request)
    {
        init_redis_session();

        $params = $request->post();
        $streamList = $this->service->queryKKStreamByUserId($params);

        Response::returnResult(Hint::SUCCESS, $streamList);
    }

    /**
     * 活动返现 钻石充值
     * */
    public function diamondRecharge(Request $request){
        $params = $request->post();
        $ret = $this->service->diamondRecharge($params);

        write_log('diamondRecharge','活动返现（钻石充值）',$ret);

        OutJson::outJsonResult($ret['code'], $ret['data']);
    }

    ################# 后台调用 ##########################################

    /**
     * 用户钱包更新
     * */
    public function walletUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'walletUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    //定时同步房间财富值
    public function sync_room_wealth()
    {
        $this->service->sync_room_wealth();
    }
    /**
     * 获取房间魅力榜冠军和财富榜冠军用户信息
     */
    public function getRoomChampion()
    {
        $room_id = $this->request->get('room_id');
        if ($room_id == null){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $model = new FinanceRoomWealth();
        $userModel = new User();
        $date = date("Ymd");

        $data = null;

        $roomInfo = (new Room())->get_room($room_id);

        //小屋和电台不显示
        if ($roomInfo['business_type'] == 0 || $roomInfo['type_id'] == 1) {
            Response::returnResult(Hint::SUCCESS, $data);
        }

        //读取当前神豪榜用户
        list($vip_user, $mvp_user,$level) = $model->getRoomVipAndMvpUser($room_id, $date);


        if($vip_user > 0 && $mvp_user > 0){
            //读取榜单值
            $mvpKey = sprintf($model->redis_charts_room_vip_mvp_charm_day, $room_id, $vip_user, $date);
            $score = Redis::zscore($mvpKey, $mvp_user);
            $score = empty($score) ? 0 : $score;

            //读取vip信息
            $user = $userModel->get_user($vip_user);
            $data['vip'] = [
                'user_id' => $user['user_id'],
                'user_uid' => $user['user_uid'],
                'nickname' => $user['nickname'],
                'image' => $user['images'][0] ?? "",
                'value' => $score
            ];

            //读取mvp信息
            $user = $userModel->get_user($mvp_user);
            $data['mvp'] = [
                'user_id' => $user['user_id'],
                'user_uid' => $user['user_uid'],
                'nickname' => $user['nickname'],
                'image' => $user['images'][0] ?? "",
                'value' => $score
            ];

            //读取等级
            $data['vip_mvp_level'] = $level;
        }

        Response::returnResult(Hint::SUCCESS,$data);
    }

    /**
     * 0点初始化房间内vip和mvp
     */
    public function roomChampionUpdate(){
        $room_ids = $this->serviceRoom->getOpenedRoomIdArr();
        foreach ($room_ids as $room_id) {
            write_log("union_cli","roomChampionUpdate",[$room_id]);
            $this->serviceRoomMsg->roomChampionUpdate($room_id, 0, 0, 0, 0);
        }
        OutJson::outJsonResult(Hint::SUCCESS);
    }

    /**校验每日消费是否达到上限 1 达到 -1 未达到
     * @param Request $request
     */
    public function checkDayConsumeIsOver(Request $request){
        $user_id = $request->get('user_id');
        $total = $request->get('price');
        $alert_id = $request->get('alert_id');

        if (empty($user_id)){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
            return;
        }
        if (empty($total)){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
            return;
        }
        if(empty($alert_id)){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
        $data = $this->service->checkAlertAndDayConsume($user_id,$total,$alert_id);

        OutJson::outJsonNoData(Hint::SUCCESS,$data ? 1 : -1);

    }

    /**
     * @desc 金币明细列表
     * @date 2018/12/20
     * */
    public function kk_exchange_detail_list()
    {
        $this->service->checkToken();

        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;

        $streamList = $this->service->getExchangeKkStreamList($page, $page_size);

        Response::returnResult(Hint::SUCCESS, $streamList);
    }
}
